package com.beiding.workordersystem.system.controller;

import com.beiding.workordersystem.common.standard.R;
import com.beiding.workordersystem.system.entity.UserEntity;
import com.beiding.workordersystem.common.vo.FindByIdsVo;
import com.beiding.workordersystem.system.vo.PasswordChangeVo;
import com.beiding.workordersystem.system.vo.UserVo;
import com.beiding.workordersystem.system.service.AccountService;
import com.beiding.workordersystem.system.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @GetMapping("/page")
    @PreAuthorize("hasAuthority('user_get')")
    R page(UserEntity userEntity, int currentPage, int pageSize) {
        return R.ok(userService.page(userEntity, currentPage, pageSize));
    }

    @PreAuthorize("hasAuthority('user_get')")
    @PostMapping("/findByIds")
    R findByIds(@RequestBody @Validated FindByIdsVo vo){
        return R.ok(userService.findByIds(vo,vo.getIds()));
    }

    @GetMapping("/details")
    @PreAuthorize("hasAuthority('user_get')")
    R details(@RequestParam String id) {
        return R.ok(userService.getById(id));
    }

    /*
    用户统一保存接口
    username字段不可变,全局唯一,非空
    name字段全局唯一,非空
    id字段为空用户新增,不为空用户修改
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('user_save')")
    R save(@RequestBody @Validated UserVo userVo) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userVo, userEntity);
        userService.save(userEntity);
        return R.ok(userEntity.getId());
    }

    @PreAuthorize("hasAuthority('user_password_reset')")
    @PostMapping("/resetPassword")
    R resetPassword(@RequestBody String[] accountIds) {
        accountService.resetPassword(accountIds);
        return R.ok();
    }

    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('user_delete')")
    R delete(@RequestBody String[] ids) {
        userService.delete(ids);
        return R.ok();
    }

    @PostMapping("/changePassword")
    R changePassword(@RequestBody @Validated PasswordChangeVo passwordChangeVo) {
        SecurityContextHolder.getContext().getAuthentication().getName();
        accountService.changePassword(passwordChangeVo.getOldPassword(), passwordChangeVo.getNewPassword());
        return R.ok();
    }

    @GetMapping("/substitution")
    @PreAuthorize("hasAuthority('user_substitution')")
    R substitution(@RequestParam String from, @RequestParam String to) {
        userService.substitution(from, to);
        return R.ok();
    }

}
